package com.demo.webapp.views.freemarker.directive.search;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.freemarker.FreemarkerManager;

import com.demo.webapp.views.freemarker.directive.core.BaseDirectiveSupport;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 自定义指令: 全文检索
 * <p/>
 * 生成检索页面
 * @author ryuu.kk
 *
 */
public class PageDirective extends BaseDirectiveSupport {

	/**
	 * 页面模板名
	 */
	private static final String PAGE_NAME = "classpath:/com/demo/webapp/views/freemarker/directive/template/search.ftl";
	
	@SuppressWarnings("rawtypes")
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		String value = "";
		String url = "";
		// 渲染模板
		String render = "";
		// 查询范围
		String scope = "";
		HttpServletRequest request = null;
		HttpServletResponse response = null;
		HttpRequestHashModel requestModel = (HttpRequestHashModel) hash.get(FreemarkerManager.KEY_REQUEST);
		if (requestModel == null) {
			throw new TemplateException("HttpRequestHashModel is null.", env);
		}
		request = requestModel.getRequest();
		value = getString("url", params, getDefaultValue("url"));
		render = getString("render", params, getDefaultValue("render"));
		scope = getString("scope", params, getDefaultValue("scope"));
		
		response = requestModel.getResponse();
		if (value.startsWith("/")) {
			value = request.getContextPath() + value;
		}
		url = response.encodeURL(value);
		//hash.put("page", page);
		hash.put("scope", scope);
		hash.put("render", render);
		hash.put("url", url);
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		try {
			path = getString("path", params, PAGE_NAME);
		} catch (TemplateModelException e) {}
		return path;
	}
	
	@Override
	public void afterInvoke(Writer writer) {
		// nothing.
	}
}
